/*
 * Copyright 2009 Max Kugland
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.splink.deepsplink.navigation {
	import org.splink.library.utils.ArrayUtils;
	import org.splink.deepsplink.navigation.command.INavigationCommand;

	/**
	 * A standard page navigation class, which conveniently enables to add a navigation
	 * for the subpages of a page. Usally it is used with the 
	 * <code>DefaultPageNavigationModel</code> and a custom 
	 * <code>IPageNavigationView</code> implementation.
	 * 
	 * @author Max Kugland
	 */
	final internal class PageNavigation implements INavigation, IPageNavigationController {
		private var _navigationCmd : INavigationCommand;
		private var _model : IPageNavigationModel;
		private var _views : Array;

		/**
		 * @param model the navigation's model
		 * @param navigationCmd the command enabeling the navigation access to the deepsplink framework
		 */
		public function PageNavigation(model : IPageNavigationModel, navigationCmd : INavigationCommand) {
			_views = new Array();
			_model = model;
			_navigationCmd = navigationCmd;
			_navigationCmd.registerNavigation(this);
		}

		/**
		 * @inheritDoc
		 */
		public function addView(view : IPageNavigationView) : IPageNavigationView {
			_views.push(view);
			view.setController(this);
			view.render(_model.getSubPageIds());
			return view;
		}

		/**
		 * @inheritDoc
		 */
		public function removeView(view : IPageNavigationView) : IPageNavigationView {
			ArrayUtils.remove(_views, view);
			return view;
		}

		/**
		 * @inheritDoc
		 */
		public function select(id : String, pageParams : Array = null, changed : Boolean = true) : void {
			if(!changed) return;
			id = _model.getSelectedPageId(id);
			if(id != null) {
				for each (var view : IPageNavigationView in _views) {
					view.select(id, pageParams, changed);
				}
			}
		}

		/**
		 * @inheritDoc
		 */
		public function gotoPage(pageId : String, pageParams : Array = null) : void {
			_navigationCmd.gotoPage(pageId, pageParams);
		}

		/**
		 * @inheritDoc
		 */
		public function finalize() : void {
			_navigationCmd.unregisterNavigation(this);
			for each (var view : IPageNavigationView in _views) {
				view.finalize();
			}
			_views.splice(0, _views.length);
			_model.finalize();
			_model = null;
			_navigationCmd = null;
		}
	}
}
